package me.zhengjie.utils;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * json工具类
 * **/
public class JsonUtil {

	private static ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	 
    public static String obj2Json(Object obj) {
    	if (obj == null) {
			return "";
		}
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            return "";
        }
    }
 
    public static <T> T json2Obj(String jsonStr, Class<T> objClass) {
    	if (StringUtil.isNullOrEmpty(jsonStr)) {
            return null;
        }
        try {
            return mapper.readValue(jsonStr, objClass);
        } catch (IOException e) {
            return null;
        }
    }
	
    /**
     * 例： JsonUtil.json2Obj(jsonStr, new TypeReference<Map<String,Student>>() {})
     * **/
    @SuppressWarnings("unchecked")
    public static <T> T json2Obj(String content, TypeReference valueTypeRef) {
        if (StringUtil.isNullOrEmpty(content)) {
            return null;
        }
        try {
            return (T) mapper.readValue(content, valueTypeRef);
        } catch (IOException e) {
        	return null;
        }
    }
    
}
